<?php

class StudentPlace_ChangeController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // 如未選擇學期,預設為本學期
        if (! $yearSemester = $this->_getParam('year_semester'))
        $yearSemester = $this->view->Semester['yearSeme'];
        $this->view->yearSemester = $yearSemester;
        $classSn = $this->_getParam('classSn');
        $this->view->classSn= $classSn;
        $sn = $this->_getParam('sn');
        if ($sn) {
            $tempArr = explode("-", $yearSemester);
            $year = (int)$tempArr[0];
            $semester = (int)$tempArr[1];
            $tempArr = explode("-", $classSn);
            $grade = (int)$tempArr[0];
            $classSn = (int)$tempArr[1];
            $tempArr = explode("-", $this->_getParam('moveTarget'));
            $tGrade = (int) $tempArr[0];
            $tClassSn = (int) $tempArr[1];
            // 先找出目標班級的最後一號
            $res = Doctrine_Query::create()
            ->select('MAX(number) as mm, class')
            ->from('Student_Model_StudentSemester')
            ->where('year=?', $year)
            ->andWhere('semester=?', $semester)
            ->andWhere('grade=?', $tGrade)
            ->andWhere('class_sn=?', $tClassSn)
            ->fetchOne();
            $i = 0;
            //更改所選學生的班級及座號
            foreach($sn as $studentSn) {
                $q = Doctrine_Query::create()
                ->update('Student_Model_StudentSemester')
                ->set('grade','?', $tGrade)
                ->set('class_sn','?', $tClassSn)
                ->set('number','?', $res->mm+$i++)
                ->set('class','?', $res->class)
                ->where('year=?', $year)
                ->andWHere('semester=?', $semester)
                ->andWhere('grade=?', $grade)
                ->andWHere('class_sn=?', $classSn)
                ->andWHere('student_sn=?', $studentSn);
                $q->execute();
            }
        }
    }

    public function getStudentAction()
    {

        $this->getHelper('layout')->disableLayout();
        $tempArr = explode("-",$this->_getParam('year_semester'));
        $year = (int) $tempArr[0];
        $semester = (int) $tempArr[1];
        $tempArr = explode("-", $this->_getParam('classSn'));
        $grade = (int) $tempArr[0];
        $classSn = (int) $tempArr[1];

        $q = Doctrine_Query::create()
        ->select('a.sn, a.name,b.student_id AS student_id, b.number AS number')
        ->from('Student_Model_Student a')
        ->leftJoin('a.Student_Model_StudentSemester b')
        ->where('b.year=?', $year)
        ->andWhere('b.semester=?', $semester)
        ->andWhere('b.grade=?', $grade)
        ->andWhere('b.class_sn=?', $classSn)
        ->andWhere('a.study_condition=?', Student_Model_Student::IN_REGISTER)
        ->orderBy('b.number');

        $res = $q->fetchArray();

        $this->view->data = $res;
    }
}

